package com.dhnsoft.代码随想录.双指针法;

/**
 * ClassName: d04_02_链表相交
 * Package: com.dhnsoft.代码随想录.双指针法
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/20 12:26
 * @Version 1.0
 */
public class d04_02_链表相交 {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null){
            return null;
        }
        if(headA==headB){
            return headA;
        }
        ListNode newNodeA = new ListNode(-1);
        ListNode newNodeB = new ListNode(-1);
        newNodeA.next = headA;
        newNodeB.next = headB;
        int lenA = ListLen(headA);
        int lenB = ListLen(headB);
        ListNode curA = newNodeA.next;
        ListNode curB = newNodeB.next;
        if(lenA>lenB){
            for (int i=0;i<lenA-lenB;i++){
                curA = curA.next;
            }
        }
        else{
            for (int i=0;i<lenB-lenA;i++){
                curB = curB.next;
            }
        }
        while (curA!=null){
            if(curA==curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;

    }

    public int ListLen(ListNode head){
        int len = 0;
        ListNode temp = head;
        while (temp.next!=null){
            len++;
            temp = temp.next;
        }
        return len;
    }
}
